package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.CaseDao;
import com.pojo.CasePojo;
import com.util.Log;

@WebServlet(urlPatterns={"/user/LoadCaseInfo"})
public class LoadCaseInfo extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		
		String indexString = request.getParameter("index");
		String pageNumber = request.getParameter("pageNumber");
		String pageSize = request.getParameter("pageSize");

		// 加载案例的下标
		int index = Integer.parseInt((indexString == null || indexString == "0") ? "1"
				: indexString);
		// 当前页
		int intPage = Integer.parseInt((pageNumber == null || pageNumber == "0") ? "1"
				: pageNumber);
		// 每页显示条数
		int number = Integer.parseInt((pageSize == null || pageSize == "0") ? "10"
				: pageSize);
		
		String message = "";
		CasePojo pojo = null;
		CaseDao dao = new CaseDao();
		// 加载按日期排序后的指定下标的案例
		pojo = dao.loadCase(intPage, number, " where 1=1 and publishStatus='1' ").get(index - 1);

		if (pojo != null) {
			message = "检索成功";
		} else {
			message = "检索失败";
		}

		String caseId = "" + pojo.getCaseId();
		String caseName = pojo.getCaseName();
		String content = pojo.getContent();

		String json = "{\"status\":\"" + message + "\", \"caseId\":\"" +caseId + "\", " +
						"\"caseName\":\"" + caseName + "\", \"content\":\"" + content + "\"}";
		dao.closeAll();
		Log.write("CaseID: " + caseId + ", " + caseName);

		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();

		out.println(json);
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
